const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { ResultSuccess, ResultError } = require('../utils/result')
const { loginCheck } = require('../utils/tools')

const handleBlogRouter = (req, res) => {
  // 博客 id
  const id = req.query.id

  // 获取博客列表
  if (req.method === 'GET' && req.path === '/api/blog/list') {
    // 获取 query
    let author = req.query.author || ''
    let keyword = req.query.keyword || ''

    if (req.query.isadmin) {
      // 管理员界面
      // 判断是否登录
      const loginCheckResult = loginCheck(req)
      if (loginCheckResult) {
        return loginCheckResult.then(data => {
          return new ResultError(data)
        })
      }
      // 强制查询自己的博客
      author = req.session.username
    }

    // 调用 controller 处理业务逻辑
    const result = getList(author, keyword)
    return result.then(data => {
      return new ResultSuccess(data)
    })
  }

  // 获取博客详情
  if (req.method === 'GET' && req.path === '/api/blog/detail') {
    const result = getDetail(id)
    return result.then(data => {
      return new ResultSuccess(data)
    })
  }

  // 新建一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/new') {
    // 判断是否登录
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult) {
      return loginCheckResult.then(data => {
        return new ResultError(data)
      })
    }
    req.body.author = req.session.username
    const result = newBlog(req.body)
    return result.then(data => {
      return new ResultSuccess(data)
    })
  }

  // 更新一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/update') {
    // 判断是否登录
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult) {
      return loginCheckResult.then(data => {
        return new ResultError(data)
      })
    }

    const result = updateBlog(id, req.body)
    return result.then(data => {
      if (data) {
        return new ResultSuccess('更新成功')
      } else {
        return new ResultError('更新失败')
      }
    })
  }

  // 删除一篇博客
  if (req.method === 'POST' && req.path === '/api/blog/del') {
    // 判断是否登录
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult) {
      return loginCheckResult.then(data => {
        return new ResultError(data)
      })
    }
    const author = req.session.username
    const result = delBlog(id, author)
    return result.then(data => {
      if (data) {
        return new ResultSuccess('删除成功')
      } else {
        return new ResultError('删除失败')
      }
    })
  }
}

module.exports = handleBlogRouter
